package io.framework.modules.air.task;

import com.alibaba.fastjson.JSONObject;
import io.framework.modules.air.entity.AirEntity;
import io.framework.modules.air.service.AirService;
import io.framework.modules.air.utils.HttpClientUtils;
import io.framework.modules.station.dto.StationDTO;
import io.framework.modules.station.service.StationService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class AirTask {

    private Logger logger = LoggerFactory.getLogger(AirTask.class);

    @Value("${sskqhttp}")
    private String sskqhttp;

    @Autowired
    private StationService stationService;

    @Autowired
    private AirService airService;

    /**
     * 实时空气数据，十分钟执行一次
     */

 //   @Scheduled(fixedDelay = 1000 * 60 * 10)
//    @Scheduled(fixedDelay = 1 * 60 * 10)
    public void task() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", 1);
        List<StationDTO> list = stationService.getStationInfoByParams(params);
        List<AirEntity> airEntityList = new ArrayList<>();
        list.stream().forEach(stationDTO -> {
            try {
                String result = HttpClientUtils.doGet(String.format("%s?url=%s", sskqhttp, "1.txt"));
                System.out.println("=========result========"+result);

                if (StringUtils.isBlank(result)) return;
                AirEntity airEntity = JSONObject.parseObject(result, AirEntity.class);
                String time = JSONObject.parseObject(result).getString("time");
                airEntity.setStationId(stationDTO.getId());
                airEntity.setType(1);
                airEntity.setCityName("三亚市");
                airEntity.setDate(new SimpleDateFormat("yyyy年MM月dd日HH时").parse(time));
                airEntity.setMonth(new SimpleDateFormat("yyyy年MM").parse(time.substring(0, time.indexOf("月"))));
                airEntity.setCreateDate(new Date());
                AirEntity ae = airService.getByStationIdAndDate(airEntity);
                if (ae == null)
                    airEntityList.add(airEntity);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        });
        if (airEntityList.size() > 0) airService.insertBatch(airEntityList);
    }

}
